<template>
  <div class="flex flex-col h-full">
    <a-card class="flex-1">
      <BaseTable :data-source="dataSource" :columns="columns" :loading="loading" max-fill :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'itemName'">
            <EditCell title="参数名">
              <SelectTable v-model:value="record.itemName" type="质控规则" @select="onSelectParameter($event, record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'qcRuleFormula'">
            <EditCell title="规则">
              <a-input v-model:value="record.qcRuleFormula" />
            </EditCell>
          </template>
        </template>
        <template #footer>
          <div class="text-center sticky bottom-0">
            <a-button class="mr-2" type="primary" ghost @click="addRow()"> 新增一行 </a-button>
            <a-button type="primary" :disabled="dataSource.length === 0" @click="saveNewRows()"> 保存 </a-button>
          </div>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import BaseTable from '@/components/BaseTable'
import { post } from '@/utils/request'
import EditCell from '@/components/EditCell'

const formState = ref({})
const loading = ref(false)
const dataSource = ref([])
const focusCell = ref('')
const editRow = (row) => !row.isNew && fetchSave(row)
const fetchSave = async (row) => {
  row.jhdh = formState.value.jhdh
  const { code, msg } = await post('/med/MedicalRecord/doSaveMrQcrule', [row])
  if (code !== 0) return message.error(msg || '操作失败')
  getDetailData()
  message.destroy()
  message.success(row.isNew ? '新增成功' : '修改成功')
}
const saveNewRows = async () => {
  const newRow = dataSource.value.filter((item) => item.isNew)
  newRow.forEach((item) => {
    if (item.qcRuleFormula) {
      fetchSave(item)
    } else {
      message.destroy()
      message.error('请填写完整信息')
    }
  })
}
const columns = ref([
  { title: '序号', dataIndex: 'outorder', width: 300 },
  { title: '参数名字', dataIndex: 'itemName', width: 300 },
  { title: '规则', dataIndex: 'qcRuleFormula', width: 300 }
])

const onSelectParameter = (medicine, row) => {
  row.itemId = medicine?.itemId
  row.itemName = medicine?.itemName
  focusCell.value = row.key
  editRow(row)
}
//添加行
const addRow = () => {
  const key = `row-${dataSource.value.length}`
  const addRow = { key, isNew: true, outorder: dataSource.value.length + 1 }
  dataSource.value.push(addRow)
}

const getDetailData = async () => {
  loading.value = true
  const { data, code } = await post('/med/MedicalRecord/getMrQcruleList', {})
  loading.value = false
  if (code === 0) {
    dataSource.value = data
  }
}
onMounted(() => {
  getDetailData()
})
</script>
<style lang="less" scoped></style>
